package JAVA300.第九章容器;

/**
 * 自定义一个hashmap,实现put方法
 */

public class TestMyHashMap {

    NodeHash[] table;//位桶数组
    int size;//存放键值对个数

    public TestMyHashMap() {
        table = new NodeHash[16];
    }

    public void put(Object key,Object value){
        NodeHash node = new NodeHash();
        node.hash = MyHash(key.hashCode(), table.length);
        node.key = key;
        node.value = value;
        node.next = null;

        //插入节点
        NodeHash temp = table[node.hash];
        NodeHash iterNode = null;//用来保存遍历时链表最后一个
        if (temp == null){
            table[node.hash] = node;
            size++;
        }else{

            while (temp!=null){//要不断迭代判断

                //判断是否有key重复，重复就要覆盖操作
                if (temp.key.equals(node.key)){
                    //cover,key next都不变 所以直接改value就ok

                    temp.value = value;
                    return;
                }else {
                    iterNode = temp;
                    temp = temp.next;

                }

            }

            iterNode.next = node;
            size++;


        }


    }


    public int MyHash(int v,int length){
        System.out.println("hash:"+(v&(length-1)));
        return v&(length-1);
    }

    public static void main(String[] args) {
        TestMyHashMap myhashMap = new TestMyHashMap();
        myhashMap.put(10,"aa");
        myhashMap.put(20,"bb");
        myhashMap.put(30,"cc");
        myhashMap.put(20,"sssss");//替换测试
        myhashMap.put(53,"qq");
        myhashMap.put(69,"kk");
        //myhashMap.put(86,"zz");


        System.out.println(myhashMap);
    }
}
